<template>
    <div class="register">
        <h3 class="register-title">免费注册</h3>
        <van-form ref="registerForm" @submit="handleRegister" validate-first>
            <mobile-field v-model="mobile"/>
            <sms-captcha-field v-model="code" :loading="captchaLoading"
                               :sending="captchaSending" :time="captchaSendingTime"
                               @finish="captchaSending = false" @send="handleSendCaptcha"/>
            <van-field :type="passwordInvisible ? 'password' : 'text'"
                       name="password" placeholder="请输入密码" center
                       v-model="password" :right-icon="passwordInvisible ? 'eye-o' : 'closed-eye'"
                       @click-right-icon="passwordInvisible = !passwordInvisible"
                       :rules="[{ required: true, message: '密码不能为空' }]"/>
            <van-field :type="passwordInvisible ? 'password' : 'text'"
                       name="confirmPassword" placeholder="请再次输入密码" center
                       v-model="confirmPassword" :right-icon="passwordInvisible ? 'eye-o' : 'closed-eye'"
                       @click-right-icon="passwordInvisible = !passwordInvisible"
                       :rules="[{ required: true, message: '密码不能为空' },
                                { validator: confirmPasswordValidator, message: '两次输入密码不一致' }]"/>
            <van-button class="register-button" type="primary" block :loading="registering">
                立即注册
            </van-button>
        </van-form>
    </div>
</template>

<script>
  import MobileField from "@/views/user/MobileField"
  import { Button, Field, Form, Toast } from "vant"
  import SmsCaptchaField from "@/views/user/SmsCaptchaField"
  import { captcha, message, security, identity } from "@mall/api-services"
  import md5 from "crypto-js/md5"

  export default {
    name: "Register",
    components: {
      SmsCaptchaField,
      MobileField,
      [Button.name]: Button,
      [Form.name]: Form,
      [Field.name]: Field,
    },
    data() {
      return {
        mobile: "",
        code: "",
        passwordInvisible: true,
        password: "",
        confirmPassword: "",
        captchaLoading: false,
        captchaSendingTime: 60000,
        captchaSending: false,
        captchaToken: "",
        registering: false,
        fromLogin: false,
      }
    },
    beforeRouteEnter(to, from, next) {
      const { name } = from
      next(vm => vm.fromLogin = name === "Login")
    },
    methods: {
      confirmPasswordValidator(confirmPassword) {
        return this.password === confirmPassword
      },
      handleSendCaptcha() {
        this.$refs.registerForm.validate("mobile")
          .then(() => {
            const { mobile } = this
            const newCaptcha = new captcha.Captcha()
            newCaptcha.type = captcha.CaptchaType.Sms
            newCaptcha.parameters = { mobile }
            this.captchaLoading = true
            captcha.CaptchaServiceV1.generateCaptcha(newCaptcha)
              .then(aCaptcha => {
                this.captchaSendingTime = aCaptcha.intervals
                this.captchaSending = true
                this.captchaToken = aCaptcha.token
              })
              .then(() => Toast("验证码已发送"))
              .then(() => {
                this.$refs.registerForm.validate("code")
              })
              .catch(({ response }) => Toast(message.getResponseMessage(response)))
              .finally(() => this.captchaLoading = false)
          })
      },
      handleRegister(values) {
        const password = md5(values.password).toString()
        const { CAPTCHA_TOKEN_PARAMETER_NAME, CAPTCHA_CODE_PARAMETER_NAME } = identity.UserRegistration
        const registration = new identity.UserRegistration()
        registration.mobile = values.mobile
        registration.password = password
        registration.mode = identity.UserRegistrationMode.Mobile
        registration.parameters = {
          [CAPTCHA_TOKEN_PARAMETER_NAME]: this.captchaToken,
          [CAPTCHA_CODE_PARAMETER_NAME]: values.code,
        }
        const { fromLogin } = this
        this.registering = true
        identity.UserServiceV1.createUser(registration)
          .then(aUser => {
            if (fromLogin) {
              this.$router.back()
            } else {
              this.$router.replace({
                path: "/login",
                query: {
                  mobile: aUser.mobile,
                  grant_type: security.GrantType.MobilePassword,
                },
              })
            }
          })
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => this.registering = false)
      },
    },
  }
</script>

<style lang="scss" scoped>
    .register {
        padding: 20px 20px;

        .register-title {
            font-size: 24px;
            line-height: 1rem;
            font-weight: 500
        }

        .register-button {
            margin-top: 30px;
        }

        ::v-deep .van-field {
            background: inherit;
            padding: 10px 0;

            .van-field__label {
                width: 70px;
                flex: initial;
            }

            &:after {
                left: 0;
            }
        }
    }
</style>
